/*
 * @Author: sympsel sympsel@outlook.com
 * @Date: 2025-07-30 17:11:56
 * @LastEditors: sympsel sympsel@outlook.com
 * @LastEditTime: 2025-07-30 18:33:52
 * @FilePath: \work25_7_30\src\LinkedList.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "SinglyLinkedList.h"

LinkedList::LinkedList() {
    _head = nullptr;
    _size = 0;
}

LinkedList::~LinkedList() {
    while (_head != nullptr) {
        Node* temp = _head;
        _head = _head->_next;
        delete temp;
    }
    _size = 0;
}

void LinkedList::InsertAtTail(int val) {
    Node* newNode = new Node(val);
    if (_head == nullptr) {
        _head = newNode;
    } else {
        Node* cur = _head;
        while (cur->_next != nullptr) {
            cur = cur->_next;
        }
        cur->_next = newNode;
    }
    _size++;
}

void LinkedList::InsertAtHead(int val) {
    Node* newNode = new Node(val);
    newNode->_next = _head;
    _head = newNode;
    _size++;
}

bool LinkedList::DeleteAtBack() {
    if (_head == nullptr) {
        return false;
    }

    Node* cur = _head;
    while (cur->_next != nullptr) {
        cur = cur->_next;
    }
    delete cur;
    _size--;
    return true;
}

bool LinkedList::DeleteAtHead() {
    if (_head == nullptr) {
        return false;
    }

    Node* temp = _head->_next;
    delete _head;
    _head = temp;
    _size--;
    return true;
}

bool LinkedList::Contains(int val) {
    for (Node* cur = _head; cur != nullptr; cur = cur->_next) {
        if (cur->_val == val) {
            return true;
        }
    }
    return false;
}

int LinkedList::FindAt(int pos) {
    if (pos < 1 || pos > _size) {
        throw std::out_of_range("Index out of range");
    }
    Node* cur = _head;
    for (; pos > 1; pos--);
    return cur->_val;
}

int LinkedList::Head() {
    if (_head == nullptr) {
        throw std::out_of_range("Empty list");
    }
    return _head->_val;
}

int LinkedList::Tail() {
    if (_head == nullptr) {
        throw std::out_of_range("Empty list");
    }
    Node* cur = _head;
    for (; cur->_next != nullptr; cur = cur->_next);
    return cur->_val;
}

void LinkedList::Print() {
    cout << "[";
    Node* cur = _head;
    for (; cur->_next != nullptr; cur = cur->_next) {
        cout << cur->_val << ", ";
    }
    cout << cur->_val;
    cout << "]" << endl;
}
